<?php
namespace app\index\controller;
use PHPExcel_IOFactory,PHPExcel;
use think\Loader;
use think\Vendor;
use think\Db;

class Phpexcelclass {

	private $PHPExcel;
	private $PHPSheet;
	private $PHPWriter;
	private $title;
	private $rows;
	private $menus;
	private $sysmenu = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
	 /*存储excel类对象*/
    private static $obpe;

    /*初始化*/
    public function __construct(){
		include '../extend/PHPExcel/Classes/PHPExcel/IOFactory.php';
    	self::$obpe = new PHPExcel();
	}

	
	/**
	 * 架构方法 设置参数
	 */
	public function construct()
	{
//		include 'extend/PHPExcel/Classes/PHPExcel/IOFactory.php';
//      require_once 'extend/PHPExcel/Classes/PHPExcel/IOFactory.php';
		self::$obpe = new PHPExcel();
	    $this->PHPExcel  = new PHPExcel();
	    $this->PHPSheet  = $this->PHPExcel->getActiveSheet();
	    $this->PHPWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel,'Excel2007');
	}

	public function downExcel($title,$rows,$menus)
	{
	    $this->title = $title;
	    $this->rows  = $rows;
	    $this->menus = $menus;
	
	    $this->PHPSheet->setTitle($this->title);
	    $this->setMenu();
	    $this->setContents();
	
	    $filename = $this->title.date("Y-m-d_H-i-s",time()).".xls";
	    ob_end_clean();
	    header("Content-Type: application/force-download");
	    header("Content-Type: application/octet-stream");
	    header("Content-Type: application/download");
	    header('Content-Disposition:inline;filename="'.$filename.'"');
	    header("Content-Transfer-Encoding: binary");
	    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	    header("Pragma: no-cache");
	    $this->PHPWriter->save('php://output');
	}
	
	public function out($mulit_arr = [],$filename = 'mulit_sheet',$Title='',$Subject='',$Description='',$Keywords='',$Category='',$type = 'output',$saveUrl = '')
    {
    	//获取用户信息
		$class = new \app\index\controller\Index();
		$accountInfo = $class->getAccountInfo();
        /* @func 设置文档基本属性 */
//      dump($mulit_arr['account']['adminName']);
        $obpe_pro = self::$obpe->getProperties();
        $obpe_pro->setCreator($mulit_arr['account']['adminName'])/*设置创建者*/
        ->setLastModifiedBy(date('Y/m/d H:i'))/*设置时间 2013/2/16 15:00*/
        ->setTitle($Title)/*设置标题*/
        ->setSubject($Subject)/*设置备注*/
        ->setDescription($Description)/*设置描述*/
        ->setKeywords($Keywords)/*设置关键字 | 标记*/
        ->setCategory($Category);/*设置类别*/

        /*
         * 设置宽度
            $obpe->getActiveSheet()->getColumnDimension()->setAutoSize(true);
            $obpe->getActiveSheet()->getColumnDimension('B')->setWidth(10);
            设置当前sheet索引,用于后续的内容操作
            一般用在对个Sheet的时候才需要显示调用
            缺省情况下,PHPExcel会自动创建第一个SHEET被设置SheetIndex=0
        */
        /*$mulit_arr*/
        foreach ($mulit_arr['data'] as $key=>$value)
        {
            /*下面这一块可以封装后 实现多个工作空间的布局发生变化*/
            $next_key = $key+1;
            /*设置SHEET*/
            self::$obpe->setactivesheetindex($key);
            /*设置工作空间名称*/
            $sheet = self::$obpe->getActiveSheet();
            $sheet->setTitle($mulit_arr['sheet'][$key]['title']);
            /*写入数据*/
            
            foreach ($value as $k=>$v)
            {
                /* @func 设置列 */
                $kkup = $k+1;
				$a = 0;
//			
                foreach ($v as $kk=>$vv)
                {
                	$where = self::getLetterByNumber($a);/*X轴 改变这个位置可以改变文档布局*/
                    $a++;
                    $x = $where.$kkup;
                    self::$obpe->getactivesheet()->setcellvalue($x,$vv);
                }
            }
            /*是否需要创建下一个工作空间*/
            if(isset($mulit_arr['data'][$next_key])){
            	self::$obpe->createSheet();
            } 
        }
        /*写入内容*/
        $obwrite = PHPExcel_IOFactory::createWriter(self::$obpe, 'Excel5');
        $filename = $filename.'.xls';
        if($type == 'output'){
            /**直接在浏览器输出*/
            header('Pragma: public');
            header('Expires: 0');
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Content-Type:application/force-download');
            header('Content-Type:application/vnd.ms-execl');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header("Content-Disposition:attachment;filename='$filename'");
            header('Content-Transfer-Encoding:binary');
			$outResult = $obwrite->save('php://output');
        }else if($type == 'saveftp'){
        	/**保存到服务器*/
        	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        	header('Pragma: public');
            header('Expires: 0');
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Content-Type:application/force-download');
            header('Content-Type:application/vnd.ms-execl');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Transfer-Encoding:binary');
			header("Content-Disposition:attachment;filename=\"$filename\"");
			header('Cache-Control: max-age=0');
			$outResult = $obwrite->save('./execl/'.$filename);//测试
			$url = $this->saveExcelToLocalFile($obwrite,$filename);
        }
//		if($outResult == 1){
			$data = [
				'listName' => $Title,
				'downTime' => date('Y-m-d H:i:s'),
				'downStatus' => 1,
				'downUrl' => $saveUrl.'/execl/'.$Title.".xls",
				'downAccount' => $accountInfo['account'],
			];
//		}else{
//			$data = [
//				'listName' => $Title,
//				'downTime' => date('Y-m-d H:i:s'),
//				'downStatus' => 0,
//				'downUrl' => $saveUrl.'/execl/'.$Title.".xls",
//				'downAccount' => $accountInfo['account'],
//			];
//		}
		Db('downloadhistory')->insert($data);
		return [
			"code" => 200,
			"message" => "导出成功",
			"outResult" => $outResult
		];
    }
    /**
     * 确定文件X横轴 # 这里暂时就弄这么多吧
     * @param int $number 传进来的就是$model的key
     * @return mixed
     */
    protected static function getLetterByNumber($number = 1)
    {
        return ['A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'][$number];
    }
	public function saveExcelToLocalFile($objWriter, $filename){ 
		// make sure you have permission to write to directory 
		$filenameGBK=iconv("UTF-8", "GBK", $filename); 
		$filePath = './execl/'.$filenameGBK.'.xls';
		$objWriter->save($filePath); 
		return str_replace('./','/','./execl/'.$filename.'.xls');
	}
}

		
		
	

?>